﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.SqlClient;
using System.Data;
using System.Configuration;
using TreaShares.Backoffice.DataLayer;
using System.Web.Security;

namespace TreaShares.Backoffice.Controlers
{
    [System.ComponentModel.DataObject]
    public class UsersManager
    {
        [System.ComponentModel.DataObjectMethod(System.ComponentModel.DataObjectMethodType.Select)]
        public MembershipUserCollection FindUsers(string searchKey, string searchByKey)
        {
            switch (searchByKey)
            {
                case "User":
                    return Membership.FindUsersByName(searchKey);
                case "Email":
                    return Membership.FindUsersByEmail(searchKey);
                case "OrganisationName":
                    return this.FindUsersByOrganisationName(searchKey);
                default:
                    return Membership.GetAllUsers();
            }
        }

        private MembershipUserCollection FindUsersByOrganisationName(string organisationNameToMatch)
        {
            MembershipUserCollection users = new MembershipUserCollection();
            using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["StrongerOrgString"].ConnectionString))
            {
                SqlCommand command = new SqlCommand();
                command.CommandType = System.Data.CommandType.StoredProcedure;
                command.Connection = conn;
                command.CommandText = "FindUsersByOrganisationName";
                command.Parameters.Add("@OrganisationNameToMatch", System.Data.SqlDbType.NVarChar, 150).Value = organisationNameToMatch;
                conn.Open();
                SqlDataReader reader = command.ExecuteReader(System.Data.CommandBehavior.SequentialAccess);
                while (reader.Read())
                {
                    string nullableString = GetNullableString(reader, 0);
                    string email = GetNullableString(reader, 1);
                    string passwordQuestion = GetNullableString(reader, 2);
                    string comment = GetNullableString(reader, 3);
                    bool boolean = reader.GetBoolean(4);
                    DateTime creationDate = reader.GetDateTime(5).ToLocalTime();
                    DateTime lastLoginDate = reader.GetDateTime(6).ToLocalTime();
                    DateTime lastActivityDate = reader.GetDateTime(7).ToLocalTime();
                    DateTime lastPasswordChangedDate = reader.GetDateTime(8).ToLocalTime();
                    Guid providerUserKey = reader.GetGuid(9);
                    bool isLockedOut = reader.GetBoolean(10);
                    DateTime lastLockoutDate = reader.GetDateTime(11).ToLocalTime();
                    users.Add(new MembershipUser("CustomizedProvider", nullableString, providerUserKey, email, passwordQuestion, comment, boolean, isLockedOut, creationDate, lastLoginDate, lastActivityDate, lastPasswordChangedDate, lastLockoutDate));
                }
            }
            return users;
        }
        private static string GetNullableString(SqlDataReader reader, int col)
        {
            if (!reader.IsDBNull(col))
            {
                return reader.GetString(col);
            }
            return null;
        }

        [System.ComponentModel.DataObjectMethod(System.ComponentModel.DataObjectMethodType.Delete)]
        public void DeleteUser(string userName)
        {
            Membership.DeleteUser(userName);
        }

        public static Guid GetClientId(string userName)
        {
            using (TreasharesDataContext db = new TreasharesDataContext())
            {
                Guid? clientId = db.aspnet_Users.Where(u => u.UserName == userName).Join(db.Clients, (u) => u.ClientId, (c) => c.Id, (u, c) => u.ClientId).FirstOrDefault();
                if (clientId.HasValue)
                {
                    return clientId.Value;
                }
                else
                {
                    return Guid.Empty;
                }
            }

        }

        internal static void UpdateUserOrganisationId(string userName, Guid organisationId)
        {
            using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ApplicationConnectionString"].ConnectionString))
            {
                SqlCommand command = new SqlCommand("UserOrganisationIdUpdate", conn);
                command.CommandType = CommandType.StoredProcedure;
                command.Parameters.Add("@UserName", System.Data.SqlDbType.NVarChar, 256).Value = userName;
                command.Parameters.Add("@ClientId", System.Data.SqlDbType.UniqueIdentifier).Value = organisationId;
                conn.Open();
                int resultCount = command.ExecuteNonQuery();

            }

        }
        [System.ComponentModel.DataObjectMethod(System.ComponentModel.DataObjectMethodType.Select)]
        public DataTable GetOrganisationUsers(string organisationId)
        {
            using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ApplicationConnectionString"].ConnectionString))
            {
                DataTable result = new DataTable();
                SqlCommand command = new SqlCommand("ClientUsersGet", conn);
                command.CommandType = CommandType.StoredProcedure;
                command.Parameters.Add("@ClientId", SqlDbType.VarChar).Value = organisationId;
                conn.Open();
                result.Load(command.ExecuteReader());
                return result;
            }
        }
        [System.ComponentModel.DataObjectMethod(System.ComponentModel.DataObjectMethodType.Select)]
        public DefaultUserSettings GetUserSettings(string userId)
        {
            using (TreasharesDataContext db = new TreasharesDataContext())
            {
                var user = db.aspnet_Users.Where(u => u.UserId == new Guid(userId)).FirstOrDefault();
                if (user.UserDefaultSettings != null)
                {
                    DefaultUserSettings dus = OrganisationManager.Deserialize<DefaultUserSettings>(user.UserDefaultSettings.ToString());
                    return dus;
                }
                else
                {
                    return new DefaultUserSettings();
                }
            }

        }
        [System.ComponentModel.DataObjectMethod(System.ComponentModel.DataObjectMethodType.Update)]
        public void UpdateUserSettings(string userId, string dateFormat, string dateFormatJS, string defaultNewTransaction, string defaultReporting, string thousandsAndDecimalSeparator)
        {
            DefaultUserSettings dus = new DefaultUserSettings()
            {
                DateFormat = dateFormat,
                DefaultNewTransaction = defaultNewTransaction,
                DefaultReporting = defaultReporting,
                ThousandsAndDecimalSeparator = thousandsAndDecimalSeparator,
                DateFormatJS = dateFormatJS,
                UserId = new Guid(userId)
            };
            using (TreasharesDataContext db = new TreasharesDataContext())
            {
                var user = db.aspnet_Users.Where(u => u.UserId == dus.UserId).SingleOrDefault();
                string userDefaultSettings = OrganisationManager.Serialize<DefaultUserSettings>(dus);
                user.UserDefaultSettings = userDefaultSettings;
                db.SubmitChanges();
            }
        }
    }
    public class DefaultUserSettings
    {
        private string defaultNewTransaction = "Stock";
        private string defaultReporting = "Transaction Listing";
        private string dateFormat = "{0:MM/dd/yyyy}";
        private string dateFormatJS = "mm/dd/yy";
        private string thousandsAndDecimalSeparator = "{0:###,###.##}";
        private int defaultNewTransactionJS = 0;
        private int defaultReportingJS = 0;
        #region Properties

        public Guid UserId { get; set; }
        public string DefaultNewTransaction { get { return defaultNewTransaction; } set { this.defaultNewTransaction = value; } }
        public string DefaultReporting { get { return this.defaultReporting; } set { this.defaultReporting = value; } }
        public string DateFormat { get { return this.dateFormat; } set { this.dateFormat = value; } }
        public string DateFormatJS { get { return this.dateFormatJS; } set { this.dateFormatJS = value; } }
        public string ThousandsAndDecimalSeparator { get { return this.thousandsAndDecimalSeparator; } set { this.thousandsAndDecimalSeparator = value; } }
        public int DefaultNewTransactionJS { get { return defaultNewTransactionJS; } set { defaultNewTransactionJS = (this.defaultNewTransaction == "Stock") ? 0 : 1; } }
        public int DefaultReportingJS { get { return defaultReportingJS; } set { defaultReportingJS = (this.DefaultReporting == "Transaction Listing") ? 0 : 1; } }

        #endregion

       
    }
}
